package com.ops.chirpit;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;



import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/** Helper class to add support for location in the status updates. */
public class LocationActivity extends Activity {
  static final String TAG = "LocationHelper";
  static final String LOC = "@loc"; // code that gets replaced with location
  public static String query = "";
  Context context = this;
  LocationManager locationManager;
  //static Location location;
  Criteria criteria;
  String bestProvider;
  ProgressThread progressThread;
  static ProgressDialog progressDialog;

  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
    locationManager = (LocationManager) context
        .getSystemService(Context.LOCATION_SERVICE);
    criteria = new Criteria();
    bestProvider = locationManager.getBestProvider(criteria, false);
    ChirpItActivity.location = locationManager.getLastKnownLocation(bestProvider);
    Log.d(TAG, "construct'd with location: " + ChirpItActivity.location);
    setContentView(R.layout.search_view);
	//Call LocationHelper to get location
    ChirpItActivity.location = LocationActivity.updateLocation();
    showDialog(ChirpItActivity.PLACES);
  }
  
  /** Returns current location */
  public static Location updateLocation() {
    Location output;
    if (ChirpItActivity.location == null) {
    	output = null;//"UNKNOWN";
    } else {
    	output = ChirpItActivity.location;//String.format("(%f,%f)", location.getLongitude(), location.getLatitude());
    }    
    return output;
  }
  
  protected Dialog onCreateDialog(int id) {
  	String title = "";
      switch(id) {
      case ChirpItActivity.PLACES:
      	title = "Places";
      	break;
      default:
      	return null;
      }
      progressDialog = new ProgressDialog(LocationActivity.this);
      progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
      progressDialog.setMessage("Loading " + title + "...");
      Message msg = Message.obtain();
      msg.arg1 = 0; msg.arg2 = 0;msg.setTarget(handler);
      progressDialog.setCancelMessage(msg);
      return progressDialog;
  }

  @Override
  protected void onPrepareDialog(int id, Dialog dialog) {
      progressDialog.setProgress(0);
      progressThread = new ProgressThread(handler, id);
      progressThread.start();
  }
  // Define the Handler that receives messages from the thread and update the progress
  final Handler handler = new Handler() {
      public void handleMessage(Message msg) {    	  
          int total = msg.arg1, max = msg.arg2;
          progressDialog.setMax(max);
          progressDialog.setProgress(total);
          if (total >= max){
              dismissDialog(ChirpItActivity.PLACES);
              ((ProgressThread) progressThread).setState(ProgressThread.STATE_DONE);
              buildPage((JSONArray) msg.obj);
          }
      }
  };
	
  public void buildPage(JSONArray places){
        final ListView lv1 = (ListView)findViewById(R.id.listView1_ref);
        final Button searchButton = (Button)findViewById(R.id.placeSearchButton);
        final Button doneButton = (Button)findViewById(R.id.placesDoneButton);
        final TextView searchText = (TextView)findViewById(R.id.textSearch);
        
        searchButton.setOnClickListener(new OnClickListener() {
        	public void onClick(View arg0){
        	    query = searchText.getText().toString();
        	    if (query !=""){
	        	    showDialog(ChirpItActivity.PLACES);
        	    }	        	    
        	}
        });
  	    doneButton.setOnClickListener(new OnClickListener() {
	        public void onClick(View arg0){
	        	Intent intent = new Intent(LocationActivity.this, ChirpItActivity.class);
	        	intent.putExtra("SOMETHING", "EXTRAS");
	        	setResult(RESULT_OK, intent);
	        	finish();
	        }
  	    });
	    if(places != null){
	        lv1.setAdapter(new CustomBaseAdapter(this, places, ChirpItActivity.PLACES));
	      	lv1.setOnItemClickListener(new OnItemClickListener() {
	      		//@Override
	      		public void onItemClick(AdapterView<?> arg0, View view,
	                int position, long id) {
	            // do whatever you want here
	              Object o = lv1.getItemAtPosition(position);
	              JSONObject fullObject = (JSONObject)o;
	              try {
	            	ChirpItActivity.attachPlace[fullObject.getInt("provider")] = fullObject.getString("id");
					Toast.makeText(LocationActivity.this, "You have chosen: " + " " + fullObject.getString("name"), Toast.LENGTH_LONG).show();
	              } catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Log.e(TAG,e.getMessage());
	              }
	      		}
	      	});
	    }
  }

  /** Converts the LOC code to current location */
  public String updateStatusForLocation(String input) {
    String output;
    if (ChirpItActivity.location == null) {
      output = input.replaceAll(LOC, "UNKNOWN");
    } else {
      output = input.replaceAll(LOC, String.format("(%f,%f)", 
    		  ChirpItActivity.location.getLatitude(), ChirpItActivity.location.getLongitude()));
    }    
    // Make sure we don't go over 140 characters
    output = (output.length() > 139) ? output.substring(0, 139) : output;
    
    Log.d(TAG, String.format("updateStatusForLocation(%s)=>%s", input, output));
    return output;
  } 
  
  public static String stringLocation(Location location){
	  return String.format("(%f,%f)", location.getLatitude(), location.getLongitude());
  }

  static double getDistance(Location location, Location placeLocation){
	double distance = 0;
	double x1 = location.getLatitude();
	double x2 = location.getLongitude();
	double y1 = placeLocation.getLatitude();
	double y2 = placeLocation.getLongitude();
	
	distance = Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)); 
	return distance;
  }
}